<template>
	<div class="notice-list-page">
		<!-- 列表加载状态 - 居中显示 -->
		<div v-if="loading" class="loading-container">
			<van-loading type="spinner" color="#1989fa" vertical> 加载中... </van-loading>
		</div>

		<!-- 通知列表 -->
		<div class="list-card-wrap" v-for="item in noticeList" :key="item.noticeId" @click="goToDetail(item)" v-show="!loading">
			<div class="title-card">
				<div class="icon-tip"></div>
				<span :class="item.isReaded != '0' ? 'isReaded' : ''">{{ item.noticeTitle }}</span>
			</div>
			<div class="info-card">
				<van-row class="mt-8">
					<van-col span="15">
						<van-icon class="time" name="https://wx.ksepia.com/profile/mini-image/do-task-time-icon.png" size="12" />
						<span class="text-value">{{ item.createTime }}</span>
					</van-col>
					<van-col span="9" class="unit">
						<van-icon name="https://wx.ksepia.com/profile/mini-image/do-task-user-icon@3x.png" size="12" />
						<span class="text-value">{{ item.createBy }}</span>
					</van-col>
				</van-row>
			</div>
		</div>

		<!-- 底部提示 -->
		<van-divider v-if="noticeList.length === total && hasScrolled && !loading" content-position="center"> 我也是有底线的 </van-divider>

		<!-- 空状态 -->
		<van-empty v-if="!loading && noticeList.length === 0" description="暂无通知" />
	</div>
</template>

<script>
import { ref, onMounted, onActivated, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getNoticeList } from '@/api/notice'

export default {
	name: 'NoticeList',
	setup() {
		const route = useRoute()
		const router = useRouter()

		// 响应式数据
		const loading = ref(false)
		const noticeList = ref([])
		const total = ref(0)
		const hasScrolled = ref(false)

		// 分页参数
		const pageNum = ref(1)
		const pages = ref(0)

		// 格式化时间的工具函数
		const formatTime = (timeStr) => {
			if (!timeStr) return ''
			const date = new Date(timeStr)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		}

		// 跳转到详情页
		const goToDetail = (item) => {
			router.push({
				path: '/notice/detail',
				query: {
					id: item.noticeId,
				},
			})
		}

		// 加载通知列表
		const loadNoticeList = async (isRefresh = false) => {
			if (isRefresh) {
				pageNum.value = 1
				noticeList.value = []
			}

			loading.value = true

			try {
				const response = await getNoticeList({
					pageNum: pageNum.value,
					pageSize: 10,
				})

				if (response.code === '0') {
					const currentList = isRefresh ? [] : noticeList.value
					const rows = response.rows.map((item) => ({
						...item,
						createTime: formatTime(item.createTime),
					}))

					noticeList.value = currentList.concat(rows)
					pages.value = response.pages
					total.value = response.total
				} else {
					showToast(response.message || '获取通知列表失败')
				}
			} catch (error) {
				console.error('获取通知列表失败:', error)
				showToast('网络错误，请稍后重试')
			} finally {
				loading.value = false
			}
		}

		// 页面上拉加载更多
		const onReachBottom = () => {
			const nextPage = pageNum.value + 1
			if (nextPage > pages.value) return

			pageNum.value = nextPage
			hasScrolled.value = true
			console.log('上拉加载更多')
			loadNoticeList()
		}

		// 处理从首页跳转的情况（已废弃，保留兼容性）
		const handleFromHomePage = () => {
			// 首页现在直接跳转到详情页，此逻辑不再需要
			// 清理可能遗留的 sessionStorage
			sessionStorage.removeItem('currentNotice')
		}

		// 监听路由query变化，实现自动刷新
		watch(
			() => route.query.refresh,
			(newVal) => {
				if (newVal) {
					console.log('检测到刷新标记，重新加载列表')
					loadNoticeList(true)
				}
			}
		)

		onMounted(() => {
			loadNoticeList(true)
			handleFromHomePage()
		})

		onActivated(() => {
			// 如果是 keep-alive 的页面，在激活时处理从首页跳转
			handleFromHomePage()
		})

		return {
			loading,
			noticeList,
			total,
			hasScrolled,
			goToDetail,
			onReachBottom,
		}
	},
}
</script>

<style lang="less" scoped>
.notice-list-page {
	padding: 16px;
	background-color: #f7f8fa;
	min-height: 100vh;
	position: relative;
}

/* 列表页面loading居中 */
.loading-container {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 1000;
}

.list-card-wrap {
	background: #fff;
	border-radius: 8px;
	margin-bottom: 12px;
	padding: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	cursor: pointer;
	transition: all 0.3s ease;

	&:active {
		transform: scale(0.98);
		background: #f8f8f8;
	}

	.title-card {
		display: flex;
		align-items: center;
		margin-bottom: 12px;

		.icon-tip {
			width: 4px;
			height: 16px;
			background: #1989fa;
			margin-right: 8px;
			border-radius: 2px;
		}

		.isReaded {
			color: #969799;
		}
	}

	.info-card {
		.mt-8 {
			margin-top: 8px;
		}

		.time {
			margin-right: 4px;
		}

		.text-value {
			font-size: 12px;
			color: #969799;
			vertical-align: middle;
			padding-left: 6px;
		}

		.unit {
			text-align: right;
		}
	}
}
</style>
